package com.aiyige.page.my.order.orderDetail;

import android.text.TextUtils;

import com.aiyige.base.api.JsonUtil;
import com.aiyige.model.OrderEntity;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.request.OrderDetailRequest;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.utils.ToastX;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by xiachao on 2018/2/6.
 */

public class OrderDetailManager {
    private static OrderDetailManager mInstance;

    /**
     * 登录管理 <BR>
     *
     * @return
     */
    public static synchronized OrderDetailManager getInstance() {
        if (mInstance == null) {
            mInstance = new OrderDetailManager();
        }
        return mInstance;
    }

    /**
     *
     * @param type 是卖家还是卖家
     * @param isOrderCode 根据orderCode查询还是默认的orderId查询
     * @param orderId
     * @param callback
     */
    public void requestOrderDetail(int type, boolean isOrderCode,String orderId,final OrderDetailCallback callback) {
        OrderDetailRequest.newBuilder().type(type).orderCode(isOrderCode?OrderDetailRequest.orderCodeType:null).id(orderId).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response != null && response.isSuccessful()) {
                        Order order = JsonUtil.toObject(response.body().string(), Order.class);
                        if (order != null && callback != null) {
                            callback.success(new OrderEntity(order));
                        }
                    } else {
                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                        onFailure(call,new Throwable(data.getMessage()));
                        if (callback != null) {
                            callback.failed();
                        }
                    }
                } catch (Exception e) {
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (callback != null) {
                    callback.failed();
                }
                if (t != null && !TextUtils.isEmpty(t.getMessage())) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    private OrderDetailModelData dataConversion(Order order) {
        return new OrderDetailModelData(order);
    }

    public interface OrderDetailCallback{
        void success(OrderEntity orderEntity);
        void failed();
    }
}
